import winreg
import datetime
import shutil
import os
import time
import ctypes
import os.path
from configparser import ConfigParser
import subprocess
import threading
import concurrent.futures
import random
from tqdm.rich import tqdm
import requests
import json
import webbrowser
import sys
import warnings
import tkinter as tk
from tkinter import filedialog

warnings.simplefilter("ignore")
requests.packages.urllib3.disable_warnings()
#获取当前执行exe的路径
pathx_pyinstaller = os.path.dirname(os.path.realpath(sys.argv[0])) + "\\output"

#下载文件函数
def download(url, save, name):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'}
    download_file = requests.get(url,headers=headers,verify=False,stream=True)
    download_file_size = int(download_file.headers['Content-Length'])/1024
    with open(file=f"{save}\\{name}", mode="wb") as f:
        for data in tqdm(iterable=download_file.iter_content(1024),total=download_file_size,unit='k',desc=f"正在下载文件...[{name}]"):
            f.write(data)

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0'
}

# 版本
V = f"1.0.5 R"
# 更新内容
up = f"1. 从根源修复了更新检测的BUG"


# well come message
def open_url(url):
    """
    打开指定的网址。

    参数:
    url (str): 要打开的网址。
    """
    # 检查是否是一个有效的网址
    if not url.startswith(('http://', 'https://')):
        url = 'http://' + url  # 如果不是，默认加上 http:// 前缀

    try:
        # 打开网址
        webbrowser.open(url)
        print(f"已成功打开网址: {url}")
    except Exception as e:
        # 如果发生错误，打印错误信息
        print(f"无法打开网址: {url}，错误信息: {e}")


def get_welcome_message():
    current_hour = datetime.datetime.now().hour

    if current_hour < 6:
        return "夜深了，早点睡觉吧~"
    elif current_hour < 12:
        return "早上好！祝您有个美好的一天~"
    elif current_hour < 18:
        return "下午好！愿您度过愉快的时光~"
    else:
        return "晚上好！祝您度过愉快的夜晚~"


# admin-test
def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False


# wget
def Get(Web, path, filename):
    pathx = os.path.dirname(os.path.abspath(__file__))
    pass
    os.system(f"{pathx}\\runing_file\\wget.exe -c -O {path}\\{filename} {Web}")


# color clss
class colors:
    HEADER = ''
    BLUE = ''
    GREEN = ''
    WARNING = ''
    FAIL = ''
    ENDC = ''
    BOLD = ''
    UNDERLINE = ''


# files move&op
def clear_terminal():
    os.system('clear')  # for macOS and Linux
    os.system('cls')


def set_terminal_title(title):
    ctypes.windll.kernel32.SetConsoleTitleW(title)


def op(out, put):
    now = datetime.datetime.now()
    current_time = now.strftime("%H:%M:%S")
    if put == "1":
        print(f"[Information：{current_time}] {out}" + colors.ENDC)
    elif put == "2":
        print(colors.GREEN + f"[Success：{current_time}] " + colors.ENDC + str(out))
    elif put == "3":
        print(colors.FAIL + f"[Error：{current_time}] " + colors.ENDC + str(out))
    elif put == "4":
        print(colors.WARNING + f"[WARNING：{current_time}] " + colors.ENDC + str(out))


def copy_and_replace(source_folder, destination_folder):
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)

    def copy_files(src, dst):
        for item in os.listdir(src):
            s = os.path.join(src, item)
            d = os.path.join(dst, item)
            if os.path.isdir(s):
                if not os.path.exists(d):
                    os.makedirs(d)
                with concurrent.futures.ThreadPoolExecutor() as executor:
                    executor.submit(copy_files, s, d)  # 在创建新的线程池中执行复制文件操作
            else:
                shutil.copy2(s, d)

    with concurrent.futures.ThreadPoolExecutor() as executor:
        executor.submit(copy_files, source_folder, destination_folder)

    executor.shutdown()  # 清理资源


def delete_directory(path):
    shutil.rmtree(path)


def delete(path_to_delete):
    delete_thread = threading.Thread(target=delete_directory, args=(path_to_delete,))
    delete_thread.start()
    delete_thread.join()


def delete_folder_content(folder_path):
    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        if os.path.isfile(file_path):
            os.remove(file_path)
        elif os.path.isdir(file_path):
            with concurrent.futures.ThreadPoolExecutor() as executor:
                executor.submit(delete_folder_content, file_path)
            os.rmdir(file_path)


def move_file(source, destination):
    def move():
        shutil.move(source, destination)

    thread = threading.Thread(target=move)
    thread.start()


def master_menu():
    set_terminal_title(f"Hypixice Hypixice Get Mincraft Lunch [{V}]")
    clear_terminal()
    print("==========主菜单=========")
    print()
    print(get_welcome_message())
    print()
    print(f"版本: {V}")
    print()
    print("1. 获取最新客户端")
    print("2. 获取最新养老服的ip")
    print("3. 公告")
    print("4. 更新内容")
    print("5. 退出")
    key = input(">")
    if key == "1":
        clear_terminal()
        op("正在获取更新检查文件...", "1")
        print("\n\n")
        time.sleep(0.1)
        get_testforVer = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/testforVer.txt",headers=headers,verify=False).text
        get_Zip_Name = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/zipname",headers=headers,verify=False).text
        op("获取成功", "2")
        time.sleep(0.1)
        clear_terminal()
        print(f"请检测即将下载版本号是否您需要的。\n\n==> {get_testforVer}\n==> 文件名称: {get_Zip_Name}\n\n更新内容：\n{get_Lunch_update_text}\n")
        Key = input("Y/N\n")

        if Key == "N":
            master_menu()
        else:
            get_Zip_Name = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/zipname",headers=headers,verify=False).text

            if os.path.isfile(f"{get_Zip_Name}"):
                op("删除上次残留文件...","1")
                os.remove(f"{ret}\\output\\{get_Zip_Name}")
                time.sleep(0.5)

            op("请选择保存目录","1")
            root = tk.Tk()
            root.withdraw()
            pathx_pyinstaller = filedialog.askdirectory(title='选择文件夹')

            
            get_download_client = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/web.txt",headers=headers,verify=False).text
            op("获取成功", "2")
            clear_terminal()
            #op(f"获取到网盘下载地址:{get_download_client}","2")
            op("正在获取直连下载地址...","1")
            get_download_client_download = json.loads(requests.put(f"https://pan.huang1111.cn/api/v3/share/download/{get_download_client.split('/')[-1]}",headers=headers,verify=False).text)
            op("获取成功","2")
            #op(f"获取到的直连链接:{get_download_client_download['data']}","2")
            op("正在获取文件名...","1")
            get_download_client_file_name = json.loads(requests.get(f"https://pan.huang1111.cn/api/v3/share/info/{get_download_client.split('/')[-1]}",headers=headers,verify=False).text)
            #op(f"获取成功,文件名是:{get_download_client_file_name['data']['source']['name']}","2")
            op("正在下载文件...","1")
            download(f"{get_download_client_download['data']}",f"{pathx_pyinstaller}",f"{get_download_client_file_name['data']['source']['name']}")
            op(f"下载完成,压缩文件保存位置:{pathx_pyinstaller}\\{get_download_client_file_name['data']['source']['name']}","2")
            input("\n\n按任意键返回住菜单。")
            file_path = f"C:\\Hypixice\\Pack.txt"
            file = open(file_path, "w")
            file.write(f"{get_Zip_Name}")
            file.close()
            master_menu()

    if key == "2":
        clear_terminal()
        op("正在获取ip地址...", "1")
        server_ip = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/ip-all.txt",headers=headers,verify=False).text
        time.sleep(0.1)
        clear_terminal()
        print(f"{server_ip}")
        input("\n\n按任意键返回住菜单。")
        master_menu()
    if key == "3":
        clear_terminal()
        op("正在获取...","1")
        get_message = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/message.txt",headers=headers,verify=False).text
        time.sleep(0.1)
        print("\n")
        clear_terminal()
        print(f"{get_message}")
        input("\n\n按任意键返回住菜单。")
        master_menu()
        
    if key == "4":
        clear_terminal()
        print(f"{up}")
        input("\n\n按任意键返回住菜单。")
        master_menu()

    if key == "5":
        sys.exit()

    else:
        master_menu()


ret = os.path.dirname(os.path.realpath(sys.argv[0]))
#test folder
def addf(name):
    if not os.path.exists(f"{ret}\\{name}"):
        os.mkdir(f"{ret}\\{name}")

addf("output")
addf("runing_file")
addf("update")
addf("updata")

#testfor Admin?
if is_admin():
    pass
else:
    op("请使用管理员权限运行！按回车退出...","3")
    input()
    exit()
#del file
def del_file(name):
    if os.path.isfile(f"{name}"):
        os.remove(f"{name}")


#检测是否有新版本的Lunch
print("正在初始化...")
del_file(f"{ret}\\updata\\main.exe")
del_file(f"C:\\Hypixice\\Pack.txt")
del_file(f"{ret}\\output\\main.zip")

ret = os.path.dirname(os.path.realpath(sys.argv[0]))
new_ver = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/update",headers=headers,verify=False).text
new_ver_text = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/update_text",headers=headers,verify=False).text
if new_ver != V:
    print(f"检测到新版本!\n\n更新内容:\n{new_ver_text}\n\n是否更新?[Y/N]")
    key=input("")
    if key == "Y" or key == "y":
        
        clear_terminal()
        op("正在获取链接...","1")
        get_download_client = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/update_d_ip",headers=headers,verify=False).text
        op("获取成功", "2")

        clear_terminal()
        #op(f"获取到网盘下载地址:{get_download_client}","2")
        op("正在获取直连下载地址...","1")
        get_download_client_download = json.loads(requests.put(f"https://pan.huang1111.cn/api/v3/share/download/{get_download_client.split('/')[-1]}",headers=headers,verify=False).text)
        op("获取成功","2")
        #op(f"获取到的直连链接:{get_download_client_download['data']}","2")
        op("正在获取文件名...","1")
        get_download_client_file_name = json.loads(requests.get(f"https://pan.huang1111.cn/api/v3/share/info/{get_download_client.split('/')[-1]}",headers=headers,verify=False).text)
        #op(f"获取成功,文件名是:{get_download_client_file_name['data']['source']['name']}","2")
        op("正在下载文件...","1")
        download(f"{get_download_client_download['data']}",f"{pathx_pyinstaller}",f"{get_download_client_file_name['data']['source']['name']}")
        op(f"下载完成,压缩文件保存位置:{pathx_pyinstaller}\\output\\{get_download_client_file_name['data']['source']['name']}","2")
        op("开始安装...","1")
        op("开始解压...","1")
        os.system(f"{ret}\\runing_file\\7z.exe x {ret}\\output\\{get_download_client_file_name['data']['source']['name']} -o{ret}\\updata")
        op("完成！","2")

        file_path = f"C:\\Hypixice\\Pack.txt"
        file = open(file_path, "w")
        file.write(f"{get_download_client_file_name['data']['source']['name']}")        
        file.close()
        subprocess.Popen(f"{ret}\\updata\\main.exe")
        sys.exit()



    else:
        pass



#检测是否有新版本的客户端
get_Zip_Name = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/zipname",headers=headers,verify=False).text
get_testforVer = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/testforVer.txt",headers=headers,verify=False).text
get_Lunch_update_text = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/update_lunch_text",headers=headers,verify=False).text
file_path = f"{ret}\\runing_file\\Pack_ver.txt"
file = open(file_path, "r")
content = file.read()
file.close()
have_new_ver_lucn="false"
if content != f"{get_Zip_Name}":
    have_new_ver_lucn="ture"
    print(f"检测到客户端已有新版本！\n\n==> {get_testforVer}\n==> 文件名称: {get_Zip_Name}\n\n更新内容：\n{get_Lunch_update_text}\n按任意键继续...")
    input()
else:
    have_new_ver_lucn="false"



#del update execute file
    
if os.path.isfile("C:\\Hypixice\\Pack.txt"):    
    file_path = ("C:\\Hypixice\\Pack.txt")
    file = open(file_path, "r")
    content = file.read()
    file.close()
    del_file(f"{ret}\\{content}")
    del_file(f"{ret}\\updata\\main.exe")
    del_file(f"C:\\Hypixice\\Pack.txt")

#seting

file_path = f"{ret}\\runing_file\\Pack_ver.txt"
file = open(file_path, "w")
if have_new_ver_lucn == "false":
    get_Zip_Name = requests.get("https://gitee.com/Hypixice/git_-master_-mc_-lunch/raw/master/zipname",headers=headers,verify=False).text
    content = file.write(f"{get_Zip_Name}")
file.close()

# main

set_terminal_title(f"Hypixice Get Mincraft Lunch  [{V}]")
clear_terminal()
print(colors.BLUE + f"")
print(colors.BLUE + f"===>Hypixice Tools<===")
print(colors.ENDC)
print(colors.WARNING + f"")
print(colors.WARNING + f"一键换端版本：{V}")
print(colors.WARNING + f"更新日期：2024/4/19")
print(colors.WARNING + f"交流群：613015467")
print(colors.WARNING + f"作者：Hypixice")
print()
print()
print(colors.GREEN + f">>>按任回车继续<<<")
input()


clear_terminal()

master_menu()
